//
//  MyConcernDataService.m
//  HZHome
//
//  Created by SunShine on 13-10-18.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "MyConcernDataService.h"
#import "UIImageView+WebCache.h"
#import "ImportantNewsItem.h"
#import "ImportantNewsCell.h"
#import "NoticesItem.h"
#import "NoticesCell.h"
#import "PolicyFileItem.h"
#import "PolicyFileCell.h"
#import "MyConcernConfigService.h"
#import "DataStoreService.h"
#import "UserInfoService.h"

@interface MyConcernDataService ()
@property (assign, nonatomic) NSInteger currentSelected;
-(CGFloat)caculateHieghtForPolicyFile:(NSInteger)row;
@end
@implementation MyConcernDataService

- (void)selectSegmentBarAtIndex:(NSInteger)selected
{
    _currentSelected = selected;
}

- (void)loadDataWithKey:(NSString *)keyOrNil
{
    _currentPageNo = 1;
    if (self.dataList) {
        self.dataList = nil;
    }
    MyConcernConfigService *configService = [MyConcernConfigService getService];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (_currentSelected == 0) {
        //要情动态
        _dataItemName = @"ImportantNewsItem";
        if (configService.selectSceneCategoryType == 1) {
            [self doHttpPost:IMPORTANT_NEWS_LIST_URL headers:nil path:[NSString stringWithFormat:@"/%d",_currentPageNo] parameters:nil];
        } else {
            if (self.delegate && [self.delegate respondsToSelector:@selector(loadDataFaild:)]) {
                [self.delegate loadDataFaild:@"您没有定制要情动态"];
            }
        }
    } else if (_currentSelected == 1) {
        //通知公告
        _dataItemName = @"NoticesItem";
//        [params setValue:[configService.selectNoticeStreetType componentsJoinedByString:@","] forKey:@"streetId"];
//        [params setValue:[configService.selectNoticeUnitType componentsJoinedByString:@","] forKey:@"unitId"];
//        [params setValue:[NSString stringWithFormat:@"'%@'",[configService.selectNoticeCategoryType componentsJoinedByString:@"','"]] forKey:@"type"];
        [params setValue:[NSString stringWithFormat:@"'%@'",[configService.selectNoticeCategoryType componentsJoinedByString:@"','"]] forKey:@"typeNoficeCategory"];
        [params setValue:[UserInfoService getUserInfoService].currentLoginUserName forKey:@"userName"];
        if (keyOrNil) {
            [params setValue:keyOrNil forKey:@"title"];
        } else {
            [params setValue:@"" forKey:@"title"];
        }
        
        [self doHttpPost:NOTICE_LIST_URL headers:nil path:[NSString stringWithFormat:@"%d",_currentPageNo] parameters:params];
        
    } else if (_currentSelected == 2) {
        //政策文件
        _dataItemName = @"PolicyFileItem";
        [params setValue:[NSString stringWithFormat:@"'%@'",[configService.selectFileRuleCategoryType componentsJoinedByString:@"','"]] forKey:@"type"];
        if (keyOrNil) {
            [params setValue:keyOrNil forKey:@"title"];
        } else {
            [params setValue:@"" forKey:@"title"];
        }
        [self doHttpPost:POLICY_FILE_URL headers:nil path:[NSString stringWithFormat:@"%d",_currentPageNo] parameters:params];
    }
}

- (void)loadMoreDataWithKey:(NSString *)keyOrNil
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    MyConcernConfigService *configService = [MyConcernConfigService getService];
    if (_currentSelected == 0) {
        //要情动态
        _dataItemName = @"ImportantNewsItem";
        if (configService.selectSceneCategoryType == 1) {
            [self doHttpPost:IMPORTANT_NEWS_LIST_URL headers:nil path:[NSString stringWithFormat:@"/%d",_currentPageNo + 1] parameters:params];
        } else {
            if (self.delegate && [self.delegate respondsToSelector:@selector(loadDataFaild:)]) {
                [self.delegate loadDataFaild:@"您没有定制要情动态"];
            }
        }
    } else if (_currentSelected == 1) {
        //通知公告
        _dataItemName = @"NoticesItem";
        [params setValue:[NSString stringWithFormat:@"'%@'",[configService.selectNoticeCategoryType componentsJoinedByString:@"','"]] forKey:@"typeNoficeCategory"];
        [params setValue:[UserInfoService getUserInfoService].currentLoginUserName forKey:@"userName"];
        if (keyOrNil) {
            [params setValue:keyOrNil forKey:@"title"];
        } else {
            [params setValue:@"" forKey:@"title"];
        }
        [self doHttpPost:NOTICE_LIST_URL headers:nil path:[NSString stringWithFormat:@"%d",_currentPageNo + 1] parameters:params];
    } else if (_currentSelected == 2) {
        //政策文件
        _dataItemName = @"PolicyFileItem";
        [params setValue:[NSString stringWithFormat:@"%@",[configService.selectFileRuleCategoryType componentsJoinedByString:@"','"]] forKey:@"type"];
        if (keyOrNil) {
            [params setValue:keyOrNil forKey:@"title"];
        } else {
            [params setValue:@"" forKey:@"title"];
        }
        [self doHttpPost:POLICY_FILE_URL headers:nil path:[NSString stringWithFormat:@"%d",_currentPageNo + 1] parameters:params];
    }
}

- (void)loadNoticeDataWithKey:(NSString *)keyOrNil title:(NSString *)title
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    MyConcernConfigService *configService = [MyConcernConfigService getService];
    if (_currentSelected == 0) {
        //要情动态
        _dataItemName = @"ImportantNewsItem";
        if (configService.selectSceneCategoryType == 1) {
            [self doHttpPost:IMPORTANT_NEWS_LIST_URL headers:nil path:[NSString stringWithFormat:@"/%d",_currentPageNo + 1] parameters:params];
        } else {
            if (self.delegate && [self.delegate respondsToSelector:@selector(loadDataFaild:)]) {
                [self.delegate loadDataFaild:@"您没有定制要情动态"];
            }
        }
    } else if (_currentSelected == 1) {
        //通知公告
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        //通知公告
        _dataItemName = @"NoticesItem";
        [params setObject:[NSString stringWithFormat:@"%@",keyOrNil] forKey:@"type"];
        [params setValue:[UserInfoService getUserInfoService].currentLoginUserName forKey:@"userName"];
        if (title) {
            [params setValue:[NSString stringWithFormat:@"%@",title] forKey:@"title"];
        }
        [self doHttpPost:NOTICE_LIST_URL headers:nil path:[NSString stringWithFormat:@"%d",_currentPageNo + 1] parameters:params];
    }
}

- (void)loadNoticeMoreDataWithKey:(NSString *)keyOrNil title:(NSString *)title
{
    _currentPageNo = 1;
    if (self.dataList) {
        self.dataList = nil;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (_currentSelected == 0) {
        //要情动态
        _dataItemName = @"ImportantNewsItem";
        [self doHttpPost:IMPORTANT_NEWS_LIST_URL headers:nil path:[NSString stringWithFormat:@"/%d",_currentPageNo + 1] parameters:params];
    } else if (_currentSelected == 1) {
        //通知公告
        _dataItemName = @"NoticesItem";
        [params setObject:[NSString stringWithFormat:@"%@",keyOrNil] forKey:@"type"];
        [params setValue:[UserInfoService getUserInfoService].currentLoginUserName forKey:@"userName"];

        if (title) {
            [params setValue:title forKey:@"title"];
        }

        [self doHttpPost:NOTICE_LIST_URL headers:nil path:[NSString stringWithFormat:@"%d",_currentPageNo ] parameters:params];
    }
}

- (CGFloat)heightForCellAtRow:(NSIndexPath *)index
{
    if (_currentSelected == 0) {
        return 88.0f;//要情动态每行88
    } else if (_currentSelected == 2){
        return [self caculateHieghtForPolicyFile:index.row] + 10.0;
    }else {
        return 44.0f;
    }
}

- (void)configCell:(UITableViewCell *)cell atIndex:(NSIndexPath *)index
{
    if (self.dataList == nil || self.dataList.count == 0) {
        return;
    }
    if (_currentSelected == 0) {
        //要情动态
        ImportantNewsItem *item = [self.dataList objectAtIndex:index.row];
        ImportantNewsCell *tempCell = (ImportantNewsCell *)cell;
        tempCell.titleLabel.text = item.title;
        tempCell.detailInfoView.text = item.detail;
        //图片
        NSString *pic = [NSString stringWithFormat:@"http://%@%@", NEWS_PIC_BASE_URL, item.picture];
        __block UIActivityIndicatorView *activityIndicator;
        __weak UIImageView *weakImageView = tempCell.imageView;
        [tempCell.imageView setImageWithURL:[NSURL URLWithString:pic] placeholderImage:[UIImage imageNamed:@"placeholder.png"] options:SDWebImageProgressiveDownload|SDWebImageRetryFailed|SDWebImageLowPriority progress:^(NSUInteger receivedSize, long long expectedSize)
         {
             if (!activityIndicator)
             {
                 [weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
                 activityIndicator.center = weakImageView.center;
                 [activityIndicator startAnimating];
             }
         } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
         {
             [activityIndicator removeFromSuperview];
             activityIndicator = nil;
         }];
    } else if (_currentSelected == 1) {
        //通知公告
        NoticesItem *item = [self.dataList objectAtIndex:index.row];
        NoticesCell *tempCell = (NoticesCell *)cell;
        tempCell.titleLabel.text = [NSString stringWithFormat:@"[%@]%@", item.type, item.title];
    } else if (_currentSelected == 2) {
        //政策文件
        PolicyFileItem *item = [self.dataList objectAtIndex:index.row];
        PolicyFileCell *tempCell = (PolicyFileCell *)cell;
        tempCell.titleTextView.text = item.title;
        tempCell.titleTextView.frame = CGRectMake(5.0, 5.0, 310.0, [self caculateHieghtForPolicyFile:index.row]);
    }
}

/**
 *	@brief	为政策文件列表的每一行单独计算textView的高度
 *
 *	@param 	row 	行号
 *
 *	@return	高度
 */
-(CGFloat)caculateHieghtForPolicyFile:(NSInteger)row

{
    PolicyFileItem *item = [self.dataList objectAtIndex:row];
    NSString *title = item.title;
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:title attributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:14.0]}];
    CGRect textRect = [attributedText boundingRectWithSize:(CGSize){310.0f, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    float fPadding = 16.0; // 8.0px x 2
    return textRect.size.height + fPadding;//cell的总高度为文本高度+留白
}


-(void)saveMyConcernConfigs
{
    MyConcernConfigService *configService = [MyConcernConfigService getService];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[NSString stringWithFormat:@"%d",configService.selectSceneCategoryType] forKey:@"typeSceneCategory"];
    [params setValue:[configService.selectNoticeStreetType componentsJoinedByString:@","] forKey:@"typeNoticeStreet"];
    [params setValue:[configService.selectNoticeUnitType componentsJoinedByString:@","] forKey:@"typeNoticeUnit"];
    [params setValue:[configService.selectNoticeCategoryType componentsJoinedByString:@","] forKey:@"typeNoticeCategory"];
    [params setValue:[configService.selectFileRuleCategoryType componentsJoinedByString:@","] forKey:@"typeRuleCategory"];
    //写入本地
    [DataStoreService saveToKeychain:[params objectForKey:@"typeSceneCategory"] data:LOCAL_IMPORTANT_NEWS_TYPE_KEY];
    [DataStoreService saveToKeychain:[params objectForKey:@"typeNoticeStreet"] data:LOCAL_NOTICE_STREET_TYPE_KEY];
    [DataStoreService saveToKeychain:[params objectForKey:@"typeNoticeUnit"] data:LOCAL_NOTICE_UNIT_TYPE_KEY];
    [DataStoreService saveToKeychain:[params objectForKey:@"typeNoticeCategory"] data:LOCAL_NOTICE_CATEGORY_TYPE_KEY];
    [DataStoreService saveToKeychain:[params objectForKey:@"typeRuleCategory"] data:LOCAL_FILE_RULE_CATEGORY_TYPE_LIST];
    //登录状态则发起请求
    if ([UserInfoService getUserInfoService].currentLoginUserName) {
        [params setValue:[UserInfoService getUserInfoService].userCustomInfo.Id forKey:@"id"];
        [params setValue:[UserInfoService getUserInfoService].userInfo.Id forKey:@"userId"];
        [params setValue:[UserInfoService getUserInfoService].userInfo.userName forKey:@"userName"];
        [self doHttpPost:USER_CONCERN_CUSTOM_URL headers:nil path:@"" parameters:params];
    } else {
        if (self.delegate && [self.delegate respondsToSelector:@selector(loadDataFinished)]) {
            [self.delegate loadDataFinished];
        }
    }
}

-(void)loadPolicyFileDetailInfo:(NSString *)itemId complete:(void (^)(id data))complete
{
    NSString *url = [NSString stringWithFormat:@"%@/%@", POLICY_FILE_DETAIL_URL, itemId];
//    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:url customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:nil httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        
        NSDictionary *json = [operation responseJSON];
        //转换对象,添加到列表中
        complete(json);
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
        //执行回调
        complete(nil);
    }];
    [currentEngine enqueueOperation:op];
}
@end
